<script setup lang="ts">

import {ref} from "vue";
import {login} from "@/api/loginAndRegister";
import {Toast} from "vant";
import router from "@/router";
import {useUserStore} from "@/store/user";

const username = ref('');
const password = ref('');

const onSubmit = async (values) => {
  const loginToast = Toast("登录中 ...");
  const loginData = await login(username.value, password.value);
  useUserStore().setUserInfo(loginData);
  Toast.clear(loginToast);

  console.log(loginData);
  await router.push("/home");
}

// 校验函数：仅允许字母和数字，长度4-10位
const validateMessage = (val: string) => /^[a-zA-Z0-9]{4,10}$/.test(val);
</script>

<template>
  <van-nav-bar title="登录"/>

  <img src="@/assets/images/img.png" alt="" class="main-img">

  <div class="qwq">
    Homie匹配，寻找专业学习伙伴
  </div>

  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="username"
          name="username"
          label="账号"
          placeholder="请输入账号"
          :rules="[{ required: true, message: '请填写账号' },
          { validator: (val) => validateMessage(val), message: '账号必须为4-10位字母或数字' }]"
      />
      <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="请输入密码"
          :rules="[{ required: true, message: '请填写密码' },
          { validator: (val) => validateMessage(val), message: '密码必须为4-10位字母或数字' }]"
      />
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit" class="submit-button">
        登录
      </van-button>
      <van-button round block type="primary" native-type="button" to="/user/register">
        注册
      </van-button>
    </div>
  </van-form>

</template>

<style scoped>
:deep(.van-nav-bar__title) {
  font-weight: bold; /* 加粗 */
}

.main-img {
  display: block; /* 让 img 变为块级元素 */
  margin: 30px auto; /* 水平居中 */
  width: 160px;
  height: 128px;
}

.qwq {
  font-weight: bold;
  text-align: center;
  font-size: 19px;
  margin: 19px 0;
}

.submit-button {
  margin-bottom: 16px;
}
</style>
